package com.learn.project2.service.wx.goods;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.learn.project2.bean.*;
import com.learn.project2.mapper.*;
import com.learn.project2.model.bo.wx.goods.GoodsListBO2;
import com.learn.project2.model.vo.wx.goods.GoodsCategoryVO2;
import com.learn.project2.model.vo.wx.goods.GoodsDetailVO2;
import com.learn.project2.model.vo.wx.goods.GoodsListVO2;
import com.learn.project2.model.vo.wx.goods.GoodsRelatedVO2;
import com.learn.project2.utils.Result;
import jdk.nashorn.internal.ir.RuntimeNode;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * \* Author: Valley
 * \* Date: 2022/1/8
 * \* Time: 21:04
 * \* Description:
 */
@Service
public class GoodsServiceImpl2 implements GoodsService2 {

    @Autowired
    MarketGoodsMapper goodsMapper;
    @Autowired
    MarketCategoryMapper categoryMapper;
    @Autowired
    MarketGoodsSpecificationMapper specificationMapper;
    @Autowired
    MarketGoodsProductMapper productMapper;
    @Autowired
    MarketGrouponMapper grouponMapper;
    @Autowired
    MarketGrouponRulesMapper grouponRulesMapper;
    @Autowired
    MarketIssueMapper issueMapper;
    @Autowired
    MarketCommentMapper commentMapper;
    @Autowired
    MarketGoodsAttributeMapper attributeMapper;
    @Autowired
    MarketBrandMapper brandMapper;
    @Autowired
    MarketSearchHistoryMapper marketSearchHistoryMapper;
    @Autowired
    MarketFootPrintMapper footPrintMapper;

    @Autowired
    MarketCollectMapper collectMapper;

    /**
     * @description: 商品总数
     * @param: []
     * @return: java.lang.Integer
     * @author 王力
     * @date: 2022-01-09 14:47:13
     */
    @Override
    public Integer goodsCount() {
        MarketGoodsExample goodsExample = new MarketGoodsExample();
        goodsExample.createCriteria().andDeletedEqualTo(false);
        long l = goodsMapper.countByExample(goodsExample);
        return (int) l;
    }

    /**
     * @description: 商品-分类-category
     * @param: [id]
     * @return: com.learn.project2.model.vo.wx.goods.GoodsCategoryVO2
     * @author 王力
     * @date: 2022-01-09 15:00:00
     */
    @Override
    public GoodsCategoryVO2 goodsCategory(Integer id) {

        GoodsCategoryVO2 categoryVO2 = new GoodsCategoryVO2();
//<<<<<<< HEAD
        MarketCategory category = categoryMapper.selectByPrimaryKey(id);
        //分情况一级类目和二级类目
        if (category.getPid() == 0) {
            //一级类目
            categoryVO2.setParentCategory(category);
            MarketCategoryExample categoryExample = new MarketCategoryExample();
            categoryExample.createCriteria().andPidEqualTo(category.getId()).andDeletedEqualTo(false);
            List<MarketCategory> brotherCategorys = categoryMapper.selectByExample(categoryExample);
            MarketCategory currentCategory = brotherCategorys.get(0);
            categoryVO2.setCurrentCategory(currentCategory);
            //取兄弟类目
            categoryVO2.setBrotherCategory(brotherCategorys);
            return categoryVO2;
        }
        //二级类目
        MarketCategory parentCategory = categoryMapper.selectByPrimaryKey(category.getPid());
        categoryVO2.setParentCategory(parentCategory);
        categoryVO2.setCurrentCategory(category);
        MarketCategoryExample categoryExample = new MarketCategoryExample();
        categoryExample.createCriteria().andPidEqualTo(category.getPid());
        List<MarketCategory> brotherCategorys = categoryMapper.selectByExample(categoryExample);
        categoryVO2.setBrotherCategory(brotherCategorys);
//=======

//        if (id < 10000){
//            MarketCategoryExample example = new MarketCategoryExample();
//            example.createCriteria();
//            example.setOrderByClause("id desc limit " + id*10 + ", 10");
//            List<MarketCategory> categories = categoryMapper.selectByExample(example);
//            categoryVO2.setCurrentCategory(categories);
//            return categoryVO2;
//        }

//        MarketCategory marketCategory = categoryMapper.selectByPrimaryKey(id);
//        categoryVO2.setParentCategory(marketCategory);
//        MarketCategoryExample categoryExample1 = new MarketCategoryExample();
//        if (marketCategory.getId() != null && marketCategory.getId() != 0){
//            categoryExample1.createCriteria().andPidEqualTo(marketCategory.getId()).andDeletedEqualTo(false);
//        }
//        List<MarketCategory> marketCategories = categoryMapper.selectByExample(categoryExample1);
//        categoryVO2.setCurrentCategory(marketCategories);
//>>>>>>> origin/master
        return categoryVO2;
    }

    /**
     * @description: 商品种类-list
     * @param: [listBO2]
     * @return: com.learn.project2.model.vo.wx.goods.GoodsListVO2
     * @author 王力
     * @date: 2022-01-09 15:27:36
     */
    @Override
    public GoodsListVO2 goodsList(GoodsListBO2 listBO2) {
        PageHelper.startPage(listBO2.getPage(), listBO2.getLimit());
        GoodsListVO2 listVO2 = new GoodsListVO2();
        MarketGoodsExample goodsExample = new MarketGoodsExample();
        MarketGoodsExample.Criteria criteria = goodsExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        if (listBO2.getIsNew() != null) criteria.andIsNewEqualTo(true);
        if (listBO2.getIsHot() != null) criteria.andIsHotEqualTo(true);
        if (listBO2.getOrder() != null && listBO2.getSort() != null) {
            goodsExample.setOrderByClause(listBO2.getSort() + " " + listBO2.getOrder());
        }
        if (listBO2.getKeyword() != null) {
            criteria.andNameLike("%" + listBO2.getKeyword() + "%");
        } else {
            if (listBO2.getCategoryId() != null && listBO2.getCategoryId() != 0)
                criteria.andCategoryIdEqualTo(listBO2.getCategoryId());
            if (listBO2.getBrandId() != null && listBO2.getBrandId() != 0)
                criteria.andBrandIdEqualTo(listBO2.getBrandId());
        }
        List<MarketGoods> marketGoods = goodsMapper.selectByExample(goodsExample);
        PageInfo<MarketGoods> pageInfo = new PageInfo<>(marketGoods);
        listVO2.setLimit(listBO2.getLimit());
        listVO2.setPage(listBO2.getPage());
        listVO2.setPages(pageInfo.getPages());
        listVO2.setTotal(pageInfo.getTotal());
        listVO2.setList(marketGoods);
        MarketCategoryExample categoryExample = new MarketCategoryExample();
        categoryExample.createCriteria().andLevelEqualTo("L2");
        List<MarketCategory> marketCategories = categoryMapper.selectByExample(categoryExample);
        listVO2.setFilterCategoryList(marketCategories);

        //wx/history微信查询搜索历史记录，插入此次查询的关键词为历史关键词insert historyKeyword。
        if (listBO2.getKeyword() != null) {
            MarketSearchHistory marketSearchHistory = new MarketSearchHistory();

            marketSearchHistory.setKeyword(listBO2.getKeyword());
            marketSearchHistory.setFrom("wx");

            //判断是否是匿名访问
            MarketUser user = (MarketUser) SecurityUtils.getSubject().getPrincipal();
            if (user != null) {
                marketSearchHistory.setUserId(user.getId());
            } else {
                marketSearchHistory.setUserId(0);
            }

            //判断插入的关键字是否表中存在，存在则更新此关键字的update
            MarketSearchHistoryExample marketSearchHistoryExample = new MarketSearchHistoryExample();
            marketSearchHistoryExample.createCriteria().andUserIdEqualTo(marketSearchHistory.getUserId()).andKeywordEqualTo(listBO2.getKeyword()).andDeletedEqualTo(false);
            List<MarketSearchHistory> marketSearchHistories = marketSearchHistoryMapper.selectByExample(marketSearchHistoryExample);
            if (marketSearchHistories.size() != 0) {
                marketSearchHistories.get(0).setUpdateTime(new Date());
                marketSearchHistoryMapper.updateByPrimaryKeySelective(marketSearchHistories.get(0));
            } else {
                marketSearchHistory.setDeleted(false);
                marketSearchHistory.setAddTime(new Date());
                marketSearchHistory.setUpdateTime(new Date());
                marketSearchHistoryMapper.insertSelective(marketSearchHistory);
            }


        }
        return listVO2;
    }

    /**
     * @description: 商品详情-detail
     * @param: [id]
     * @return: com.learn.project2.model.vo.wx.goods.GoodsDetailVO2
     * @author 王力
     * @date: 2022-01-09 16:23:57
     */
    @Transactional
    @Override
    public GoodsDetailVO2 goodsDetail(Integer id) {
        GoodsDetailVO2 detailVO2 = new GoodsDetailVO2();

        MarketGoods marketGoods = goodsMapper.selectByPrimaryKey(id);

        MarketGoodsSpecificationExample specificationExample = new MarketGoodsSpecificationExample();
        specificationExample.createCriteria().andGoodsIdEqualTo(id).andDeletedEqualTo(false);
        List<MarketGoodsSpecification> specifications = specificationMapper.selectByExample(specificationExample);
        List<GoodsDetailVO2.Specification> specificationList = new ArrayList<>();
        for (MarketGoodsSpecification specification : specifications) {
            GoodsDetailVO2.Specification spec = new GoodsDetailVO2.Specification();
            spec.setName(specification.getSpecification());
            spec.setValueList(specifications);
            specificationList.add(spec);
        }
        detailVO2.setSpecificationList(specificationList);

        MarketGrouponRulesExample grouponRulesExample = new MarketGrouponRulesExample();
        grouponRulesExample.createCriteria().andGoodsIdEqualTo(id).andDeletedEqualTo(false);
        List<MarketGrouponRules> grouponRules = grouponRulesMapper.selectByExample(grouponRulesExample);
        detailVO2.setGroupon(grouponRules);

        MarketIssueExample issueExample = new MarketIssueExample();
        issueExample.createCriteria().andDeletedEqualTo(false);
        issueExample.setOrderByClause("id desc limit 4");
        List<MarketIssue> marketIssues = issueMapper.selectByExample(issueExample);
        detailVO2.setIssue(marketIssues);


        MarketUser user = (MarketUser) SecurityUtils.getSubject().getPrincipal();
        if (user != null) {
            MarketCollectExample collectExample = new MarketCollectExample();
            collectExample.createCriteria().andUserIdEqualTo(user.getId()).andValueIdEqualTo(id).andDeletedEqualTo(false);
            List<MarketCollect> collects = collectMapper.selectByExample(collectExample);
            if (collects.size() != 0) detailVO2.setUserHasCollect(1);
        } else detailVO2.setUserHasCollect(0);


        detailVO2.setShareImage(marketGoods.getPicUrl());

        GoodsDetailVO2.CommentBean commentBean = new GoodsDetailVO2.CommentBean();
        MarketCommentExample commentExample = new MarketCommentExample();
        commentExample.createCriteria().andValueIdEqualTo(id).andDeletedEqualTo(false);
        commentExample.setOrderByClause("id desc limit 4");
        List<MarketComment> marketComments = commentMapper.selectByExample(commentExample);
        commentBean.setData(marketComments);
        commentBean.setCount(marketComments.size());
        detailVO2.setComment(commentBean);


        detailVO2.setShare(false);

        MarketGoodsAttributeExample attributeExample = new MarketGoodsAttributeExample();
        attributeExample.createCriteria().andGoodsIdEqualTo(id).andDeletedEqualTo(false);
        List<MarketGoodsAttribute> goodsAttributes = attributeMapper.selectByExample(attributeExample);
        detailVO2.setAttribute(goodsAttributes);

        MarketGoods goods = goodsMapper.selectByPrimaryKey(id);
        MarketBrand marketBrand = brandMapper.selectByPrimaryKey(goods.getBrandId());
        detailVO2.setBrand(marketBrand);

        MarketGoodsProductExample productExample = new MarketGoodsProductExample();
        productExample.createCriteria().andGoodsIdEqualTo(id).andDeletedEqualTo(false);
        List<MarketGoodsProduct> marketGoodsProducts = productMapper.selectByExample(productExample);
        detailVO2.setProductList(marketGoodsProducts);

        detailVO2.setInfo(marketGoods);

        //添加到足迹
        MarketFootPrint footPrint = new MarketFootPrint(null,user.getId(),marketGoods.getId(),new Date(),new Date(),false);
        footPrintMapper.insert(footPrint);

        return detailVO2;
    }

    /**
     * @description: 商品详情-related
     * @param: [id]
     * @return: com.learn.project2.model.vo.wx.goods.GoodsRelatedVO2
     * @author 王力
     * @date: 2022-01-09 22:16:16
     */
    @Override
    public GoodsRelatedVO2 goodsRelated(Integer id) {
        PageHelper.startPage(6, 1);
        GoodsRelatedVO2 relatedVO2 = new GoodsRelatedVO2();
        relatedVO2.setLimit(6);
        relatedVO2.setPage(1);
        MarketGoodsExample goodsExample = new MarketGoodsExample();
        goodsExample.createCriteria().andCategoryIdEqualTo(id).andDeletedEqualTo(false);
        List<MarketGoods> marketGoods = goodsMapper.selectByExample(goodsExample);
        PageInfo<MarketGoods> pageInfo = new PageInfo<>(marketGoods);
        relatedVO2.setTotal(pageInfo.getTotal());
        relatedVO2.setPages(pageInfo.getPages());
        relatedVO2.setList(pageInfo.getList());
        return relatedVO2;
    }


}
